package org.saxonextensions.examples.jboss;

import net.sf.saxon.Controller;
import org.jboss.annotation.ejb.Service;
import org.jboss.logging.Logger;
import org.saxonextensions.CachingTransformerFactory;
import org.saxonextensions.eml.emitter.DevNullResult;
import org.saxonextensions.eml.emitter.ExtendedlOutputResolver;

import javax.ejb.EJBException;
import javax.ejb.Local;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamSource;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;

/**
 * Email Emitter JBoss example
 *
 * @author Ivan Latysh
 * @since 22-Jan-2009 8:18:22 PM
 */
@Service
@Local(EmailEmitterExampleLocal.class)
public class EmailEmitterExample implements EmailEmitterExampleLocal, EmailEmitterExampleManagement {

  /** Component logger */
  protected Logger logger = Logger.getLogger(this.getClass().getName());

  // Saxon caching transformer factory
  protected final TransformerFactory factory = new CachingTransformerFactory();

  public void create() throws Exception {
    logger.info(">>> Created"); 
  }

  public void start() throws Exception {
    logger.info(">>> Started");
    // send test email
    sendEmail();
  }

  public void stop() {
    logger.info(">>> Stopped");
  }

  public void destroy() {
    logger.info(">>> Destroyed");
  }

  /**
   * Sent a test email
   */
  public void sendEmail() {
    String template = "xslt/test-email.xslt";
    Transformer transformer;
    StreamSource source;
    InputStream in = null;
    try {

      // Load the template
      in = this.getClass().getClassLoader().getResourceAsStream(template);
      if (null==in) {
        throw new Exception("Unable to load email template {"+template+"}.");
      }

      // get the transformer
      source = new StreamSource(in);
      
      synchronized (factory) {
        transformer = factory.newTransformer(source);
      }
      // register output URI Resolver
      if (transformer instanceof Controller) {
        ((Controller)transformer).setOutputURIResolver(new ExtendedlOutputResolver());
      }

      // prepare test source
      Source xmlSource = new StreamSource(new StringReader("<test/>"));

      // execute transformation
      transformer.transform(xmlSource, new DevNullResult());
    } catch (Exception e) {
      e.printStackTrace();
      throw new EJBException("Unable to send an Email", e);
    } finally {
      if (null!=in) {
        try {
          in.close();
        } catch (IOException e) {
          logger.debug("Unable to close input stream for {"+template+"}", e);
        }
      }
    }
  }

}